<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box1 {
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
        left: 0;
      }
    </style>
    <script>
      function getStyle(obj, name) {
        if (window.getComputedStyle) {
          return getComputedStyle(obj, null)[name];
        }
      }
      window.onload = function () {
        var box1 = document.getElementById("box1");
        var btn01 = document.getElementById("btn01");
        var btn02 = document.getElementById("btn02");

        // /定义一个变量，用来保存定时器的标识
        var timer;
        btn01.onclick = function () {
          clearInterval(timer);
          timer = setInterval(function () {
            // 获取box1原来的left值
            var oldValue = parseInt(getStyle(box1, "left"));
            var newValue = oldValue + 10; //移动的速度
            if (newValue > 800) {
              newValue = 800;
            }
            // 将新值设置给box1
            box1.style.left = newValue + "px";
            if (newValue === 800) {
              clearInterval(timer);
            }
          }, 30);
        };
        btn02.onclick = function () {
          clearInterval(timer);
          timer = setInterval(function () {
            // 获取box1原来的left值
            var oldValue = parseInt(getStyle(box1, "left"));
            var newValue = oldValue + -10; //移动的速度
            if (newValue < 0) {
              newValue = 0;
            }
            // 将新值设置给box1
            box1.style.left = newValue + "px";
            if (newValue === 0) {
              clearInterval(timer);
            }
          }, 30);
        };
      };
    </script>
  </head>
  <body>
    <button id="btn01">点击按钮后div向右移动</button>
    <button id="btn02">点击按钮后div向左移动</button>
    <div id="box1"></div>
  </body>
</html>
